//
//  SelectLocationViewController.m
//  didacar
//
//  Created by 度周末网络-王腾 on 15/11/27.
//  Copyright © 2015年 dzmmac. All rights reserved.
//

#import "SelectLocationViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchAPI.h>
#import "NSString+Additions.h"
#import "SelectedPoisCell.h"
#import "LoadingTableCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "SearchPoisCell.h"
#import "LocationSearchViewModel.h"
#import "UISearchBar+Style.h"
#import "CommoneTools.h"
#import "UIButton+Dzm.h"
@interface SelectLocationViewController () <AMapSearchDelegate,MAMapViewDelegate,UISearchBarDelegate>

@property (strong, nonatomic) LocationSearchViewModel *locationSearchViewModel;

@property (nonatomic, assign) CLLocationCoordinate2D userCLLocation;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *mapBgViewConstraint;


@property (strong, nonatomic) IBOutlet UITableView *mainTable;
@property (strong, nonatomic) IBOutlet MAMapView *mapView;


@property (weak, nonatomic) IBOutlet UIImageView *locationImg;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *oneConstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *twoConstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *threeConstraint;

/*  搜索相关  */
@property (weak,   nonatomic) IBOutlet UIView *searchTableBgView;
@property (weak,   nonatomic) IBOutlet UITableView *searchMainTable;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (assign, nonatomic) NSInteger showBtnIndex;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *address_height_layout;
@property (weak, nonatomic) IBOutlet UIView *commoneAddressView;


@end

@implementation SelectLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configMap];
    
    if (self.isHiddenCommoneAddress) {
        self.address_height_layout.constant = 0.1;
    }
    
    self.locationSearchViewModel = [[LocationSearchViewModel alloc ] init];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width
                                                                           , 44)];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = self.searchBarPlaceholder;
    self.navigationItem.titleView = self.searchBar;
    
    self.mapBgViewConstraint.constant = GTFixHeightFloat(210);
    
    self.loadingCell = [LoadingTableCell getIntance];
    
    self.oneConstraint.constant = 0.5;
    self.twoConstraint.constant = 0.5;
    self.threeConstraint.constant = 0.5;
    
    [self setLeftCloseBtnItem];
    
    [self setExtraCellLineHidden:self.mainTable];
}

-(void)closeAction{
    
    if (self.locationSearchViewModel.isSearch) {
        
        [self closeSearch];
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}


-(void)closeSearch{
    self.locationSearchViewModel.isSearch = NO;
    [self.searchBar resignFirstResponder];
    WEAKSELF
    [UIView animateWithDuration:0.1 animations:^{
        weakSelf.searchTableBgView.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf.searchTableBgView removeFromSuperview];
    }];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    self.locationSearchViewModel.searchPageIndex = 1;
    self.locationSearchViewModel.requestTip = searchText;
    
    WEAKSELF
    [self.locationSearchViewModel requestTipReslutBlock:^(NSInteger resultType, id data, NSString *errorMsg) {
        [weakSelf.searchMainTable reloadData];
    }];
   
}

-(void)loadMorePoiSearch{
    WEAKSELF
    [self.locationSearchViewModel loadMorePoiSearchReslutBlock:^(NSInteger resultType, id data, NSString *errorMsg) {
        [weakSelf.mainTable reloadData];
    }];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    
    if (self.locationSearchViewModel.isSearch) {
        return YES;
    }
    self.locationSearchViewModel.isSearch = YES;
    self.searchTableBgView.frame = self.view.bounds;
    [self.view addSubview:self.searchTableBgView];
    self.searchTableBgView.alpha = 0;
    WEAKSELF
    [UIView animateWithDuration:0.1 animations:^{
        weakSelf.searchTableBgView.alpha = 1;
    }];
    return YES;
}

-(void)configMap{
    
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeNone;
    self.mapView.showsScale = NO;
    self.mapView.showsCompass = NO;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    if (self.userCLLocation.latitude && self.userCLLocation.longitude)
    return;
    self.userCLLocation = userLocation.location.coordinate;
    MACoordinateSpan macoordinateSpan;
    macoordinateSpan.latitudeDelta = 0.007;
    macoordinateSpan.longitudeDelta= 0.007;
    MACoordinateRegion macoordinateRegion = MACoordinateRegionMake(userLocation.location.coordinate, macoordinateSpan);
    [self beginSearch:userLocation.location.coordinate];
    
    WEAKSELF
    [self.locationSearchViewModel  requestGoecodeSearch:userLocation.location.coordinate reslutBlock:^(NSInteger resultType, id data, NSString *errorMsg) {
        [weakSelf.mainTable reloadData];
    }];
    [self.mapView setRegion:macoordinateRegion animated:YES];
}

// 显示位置
-(void)setRegion:(double)latitudeDelta longitudeDelta:(double)longitudeDelta{
    
    CLLocationCoordinate2D cLLocation;
    cLLocation.latitude = latitudeDelta;
    cLLocation.longitude= longitudeDelta;
    
    MACoordinateSpan macoordinateSpan;
    macoordinateSpan.latitudeDelta = 0.007;
    macoordinateSpan.longitudeDelta= 0.007;
    MACoordinateRegion macoordinateRegion = MACoordinateRegionMake(cLLocation, macoordinateSpan);
    [self.mapView setRegion:macoordinateRegion animated:YES];
    
//    MAPointAnnotation *a1 = [[MAPointAnnotation alloc] init];
//    a1.coordinate = cLLocation;
//    [self.mapView addAnnotation:a1];
}

/*!
 @brief 地图区域改变完成后会调用此接口
 */
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    if (self.userCLLocation.latitude && self.userCLLocation.longitude && !animated){
        CGPoint markPoint = CGPointMake(self.locationImg.center.x, self.locationImg.center.y + (self.locationImg.frame.size.height * 0.5));
        CLLocationCoordinate2D location = [self.mapView convertPoint:markPoint toCoordinateFromView:self.mapView];
        [self beginSearch:location];
    }
}

-(void)beginSearch:(CLLocationCoordinate2D)corrdinate{
    
    self.locationSearchViewModel.pageIndex = 1;
    WEAKSELF
    [self.locationSearchViewModel requestPoi:corrdinate reslutBlock:^(NSInteger resultType, id data, NSString *errorMsg) {
        [weakSelf.mainTable reloadData];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.locationSearchViewModel.isSearch){
        // 还有数据
        if (self.locationSearchViewModel.searchBMore){
            return self.locationSearchViewModel.searchPois.count + 1;
        }
        return self.locationSearchViewModel.searchPois.count;
    }else{
        // 还有数据
        if (self.locationSearchViewModel.bMore){
            return self.locationSearchViewModel.pois.count + 1;
        }
        return self.locationSearchViewModel.pois.count;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.locationSearchViewModel.isSearch){
        
        [self closeSearch];
        
        PoisModel *poisModel = self.locationSearchViewModel.searchPois[indexPath.row];
        [self setRegion:poisModel.latitude longitudeDelta:poisModel.longitude];
        [self beginSearch:CLLocationCoordinate2DMake(poisModel.latitude, poisModel.longitude)];
        
    }else{
        PoisModel *poisModel = self.locationSearchViewModel.pois[indexPath.row];
        [self setRegion:poisModel.latitude longitudeDelta:poisModel.longitude];
        self.showBtnIndex = indexPath.row;
        [tableView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.locationSearchViewModel.isSearch){
        if (indexPath.row  < self.locationSearchViewModel.searchPois.count){
            return [tableView fd_heightForCellWithIdentifier:@"SearchPoisCell" configuration:^(id cell) {
                SearchPoisCell *poiCell = cell;
                PoisModel *poisModel = self.locationSearchViewModel.searchPois[indexPath.row];
                poiCell.searchKeyWord = self.searchBar.text;
                [poiCell setModel:poisModel];
                
            }];
        }else{
            return 44;
        }
    }else{
        if (indexPath.row  < self.locationSearchViewModel.pois.count){
            return [tableView fd_heightForCellWithIdentifier:@"SelectedPoisCell" configuration:^(id cell) {
                SelectedPoisCell *poiCell = cell;
                PoisModel *poisModel = self.locationSearchViewModel.pois[indexPath.row];
                poiCell.name.text = poisModel.name;
                poiCell.address.text = poisModel.address;
            }];
        }else{
            return 44;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.locationSearchViewModel.isSearch){
        if (indexPath.row  < self.locationSearchViewModel.searchPois.count){
            SearchPoisCell *poiCell = [tableView dequeueReusableCellWithIdentifier:@"SearchPoisCell"];
            PoisModel *poisModel = self.locationSearchViewModel.searchPois[indexPath.row];
            poiCell.searchKeyWord = self.searchBar.text;
            [poiCell setModel:poisModel];
            
            return poiCell;
        }
        else{
            if (self.locationSearchViewModel.searchBMore){
                self.locationSearchViewModel.searchBMore = NO;
                self.locationSearchViewModel.searchPageIndex ++;
                
                WEAKSELF
               [self.locationSearchViewModel loadMoreTipSearchReslutBlock:^(NSInteger resultType, id data, NSString *errorMsg) {
                   
                   
                   [weakSelf.searchMainTable reloadData];
               }];
            }
            return self.loadingCell;
        }
    }else{
        if (indexPath.row  < self.locationSearchViewModel.pois.count){
            SelectedPoisCell *poiCell = [tableView dequeueReusableCellWithIdentifier:@"SelectedPoisCell"];
            PoisModel *poisModel = self.locationSearchViewModel.pois[indexPath.row];
            poiCell.name.text = poisModel.name;
            poiCell.address.text = poisModel.address;
            poiCell.btn.tag = indexPath.row;
            if (self.showBtnIndex == indexPath.row) {
                poiCell.btn.hidden = NO;
            }else{
                poiCell.btn.hidden = YES;
            }
            WEAKSELF
            [poiCell.btn addActionHandler:^(UIButton *btn) {
                PoisModel *poisModel = self.locationSearchViewModel.pois[btn.tag];
                
                if (btn.tag == 0) {
                    poisModel.name = [poisModel.name stringByReplacingOccurrencesOfString:@"[我的位置]" withString:@""];
                }
                
                if (weakSelf.delegate) {
                    [weakSelf.delegate selectedPoiModel:poisModel];
                    [weakSelf dismissViewControllerAnimated:YES completion:NULL];
                }
            }];
            
            return poiCell;
        }
        else{
            if (self.locationSearchViewModel.bMore){
                self.locationSearchViewModel.bMore = NO;
                self.locationSearchViewModel.pageIndex ++;
                [self loadMorePoiSearch];
                
            }
            return self.loadingCell;
        }
    }
}

-(void)dealloc{
    
    self.mapView.delegate = nil;
    NSLog(@"%s",__func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
